//
//  RTTextView.swift
//  Weibo
//
//  Created by Brisinga on 16/3/13.
//  Copyright © 2016年 Root. All rights reserved.
//

import UIKit

@IBDesignable
class RTTextView: UITextView {
    
    // 设置placeholder
    @IBInspectable var placeholder: String? {
    
        didSet {
        
            placeHolderLabel.text = placeholder
        }
    }
    
    // 重写font的set方法
    override var font: UIFont? {
    
        didSet {
        
            placeHolderLabel.font = font
        }
    }
    
    // 重写textSet方法
    override var text: String? {
        
        didSet {
        
            placeHolderLabel.hidden = hasText()
        
        }
        
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        
        super.init(coder: aDecoder)
        
        setupUI()
    }
    
    
    // 初始化内部控件
    private func setupUI() {
    
        addSubview(placeHolderLabel)
        
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            
            make.leading.equalTo(self).offset(5)
            make.top.equalTo(self).offset(8)
            make.width.equalTo(kScreenWidth - 10)
        }
        
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChanged", name: UITextViewTextDidChangeNotification, object: nil)
    }
    
    // 隐藏placeholder
    @objc private func textChanged() {
        
        placeHolderLabel.hidden = hasText()
    }
    
    // 懒加载placeHolderLabel
    private lazy var placeHolderLabel: UILabel = {
    
        let placeHolderLabel = UILabel()
        
        placeHolderLabel.textColor = UIColor.lightGrayColor()
        
        placeHolderLabel.numberOfLines = 0
        
        placeHolderLabel.text = "我要带你到处去飞翔,走遍世界各地去观赏,没有烦恼没有那悲伤,自由自在身心多开朗"
        
        placeHolderLabel.font = UIFont.systemFontOfSize(12)
        
        return placeHolderLabel
    }()
    
    // 移除监听者
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
